// pages/draw/index.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type:1,
    logo:'',
    logotemp:'',
    picname:'https://img.bestsmartbee.com/1537087798085',
    pictemp:'',
    page:'pages/card/info',
    scene:3,
    coverInfo:{},
    title:'5折优惠券',
    shareText:'妈呀！这家店的太好吃了，快来领取优惠券！',
    window: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ extConfig: app.getExtConfigSync(), shopInfo: app.getShopInfo() })
    var userinfo = wx.getStorageSync('user_info');
    var window = wx.getSystemInfoSync();
    var boxHeight = window.windowHeight-100;
    var boxWidth = window.windowWidth-20;
    boxWidth = boxWidth > window.windowWidth ? window.windowWidth : boxWidth;
    this.setData({ userinfo:userinfo,window: window, boxWidth: boxWidth, boxHeight: boxHeight, imageCoverWidth: boxWidth - 30, icoWidth: boxWidth * 0.2, textareaWidth: boxWidth*0.65});
    if (options.title) {
      this.data.title = decodeURIComponent(options.title);
      this.setData({title: this.data.title});
    }
    if (options.picname) {
      this.data.picname = decodeURIComponent(options.picname);
      this.setData({ picname: this.data.picname });
    }
    if (options.page) {
      this.data.page = decodeURIComponent(options.page);
    }
    if (options.scene) {
      this.data.scene = decodeURIComponent(options.scene);
    }
    if (options.shareText) {
      this.data.shareText = decodeURIComponent(options.shareText);
      this.setData({ shareText: this.data.shareText });
    }

    this.getLogo();
    this.downloadFile(this.data.picname,"pictemp");
   
  },
 
  getLogo:function(){
     var that = this;
    // var logo = app.data.apiHost+'user/getLogo?id='+this.data.id;
    // /api/index / getWxacode ? page = pages / card / info & scene=3 & appid=wx9f32634252113a93
    var logo = app.getUrl("/api/index/getWxacode",{
      page: this.data.page,
      scene: this.data.scene,
    })
    that.setData({ logo: logo });
    that.downloadFile(logo);
  },
 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },
  
  cutText:function(text){
   var shareText=[];
   var word = 16;
   var max = text.length;
   var tmptext="";
   var count = 1;
   for (var i in text){
     tmptext += text[i];
     if (count == word){
       shareText.push(tmptext);
       tmptext="";
       count=0;
     }
     count++;
   }
   //console.log("cou",count,'max',max);
   if (count < max+2) {
     shareText.push(tmptext);
   }
   console.log(shareText);
   return shareText;
  },

  formSubmit: function (e) {
    
    var postData = e.detail.value;
    var text = postData.shareText;
    if (text.length==0){
      app.alert("请输入分享文字");
    }
    if (this.data.logotemp.length==0){
     // app.alert("请等待图片加载完成");
      wx.showToast({
        title: '正在加载图片...',
        icon: 'loading',
        duration: 5000
      });
      return false;
    }
    if (this.data.pictemp.length == 0) {
      // app.alert("请等待图片加载完成");
      wx.showToast({
        title: '正在加载图片...',
        icon: 'loading',
        duration: 5000
      });
      return false;
    }
    this.setData({ type:2});
    var shareText =  this.cutText(text);
   // console.log(text);
    //console.log(shareText);
    // var shareText = [];
    // shareText[0] = '“我好啊！位置都会变。';
    // shareText[1] = "不知道还有没有其他方法让他居中显示”";
    var logo = this.data.logotemp;
   // var logo = '/image/gh_87bdb895ea90_430.jpg';
    var cover = this.data.pictemp;
    const ctx = wx.createCanvasContext('myCanvas');
    //背景色
    var imgBoxW = this.data.boxWidth ;
    var imgBoxH = this.data.boxHeight-60;
    ctx.setFillStyle('#ffffff');
    ctx.fillRect(0, 0, this.data.boxWidth, this.data.boxHeight);
    this.data.imgBoxW = imgBoxW;
    this.data.imgBoxH = imgBoxH;
    //图片层
    // var imgBoxW = this.data.boxWidth - 20;
    // var imgBoxH = this.data.boxHeight - 90;
    // ctx.setFillStyle('#ffffff');
    // ctx.fillRect(10, 80, imgBoxW, imgBoxH);
    //标题
    ctx.setTextAlign('center');
    ctx.setFontSize(18);
    ctx.setFillStyle('#444444')
    ctx.fillText(this.data.title, this.data.boxWidth*0.5, 50);
    //封面
    var coverInfo = this.data.coverInfo;
    console.log(coverInfo);
    var imageCoverWidth = imgBoxW -40;
    
    var imageHight = (imageCoverWidth / coverInfo.width) * coverInfo.height;
    var maxH = imgBoxH*0.45;
    var imageCoverH = imageHight;
    //高图片
    if (imageCoverH > maxH){
      imageCoverH = maxH;
      imageCoverWidth = (maxH / coverInfo.height) * coverInfo.width
    }
    var left = (imgBoxW-imageCoverWidth)/2;
    ctx.drawImage(cover, left, 70, imageCoverWidth, imageCoverH );
    
 
    //小目标文字
    var top = imageCoverH + 100;
    ctx.setFillStyle('#444444')
    ctx.setFontSize(16);
    ctx.setTextAlign('center');
    var step =0;
    for (var i in shareText){
      step = i * 16*1.5;
      ctx.fillText(shareText[i], imgBoxW * 0.5, top+step);
    }
    console.log(logo);
    //二维码
    var imageCoverWidth = imgBoxW * 0.2;
    var top = this.data.boxHeight - imageCoverWidth - imageCoverWidth*0.5-20;
    var left = imgBoxW * 0.4 ;
    ctx.drawImage(logo, left, top, imageCoverWidth, imageCoverWidth);

    //版权
    var top = this.data.boxHeight-20;
    ctx.setFillStyle('#666666')
    ctx.setFontSize(12);
    ctx.setTextAlign('center');
    ctx.fillText("@"+this.data.shopInfo.name+"，长按二维码查看", imgBoxW * 0.5 , top );
    ctx.draw()

    
   
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  canle:function(){
   this.setData({type:1});
  },
  navigateBack:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  canvasSave:function(){
    wx.showToast({
      title: '正在生成图片...',
      icon: 'loading',
      duration: 5000
    });
    var destWidth = 1200;
    var destHeight = (destWidth / this.data.imgBoxW) * this.data.imgBoxH;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      // width: 50,
      // height: 50,
      destWidth: destWidth,
      destHeight: destHeight,
      canvasId: 'myCanvas',
      fail: function (res){
        console.log(res);
      },
      success: function (res) {
        console.log(res.tempFilePath)
        wx.saveImageToPhotosAlbum({ 
          filePath: res.tempFilePath,
          success:function(){
            app.alert("图片保存成功，可到相册查看");
          },
          fail: function (res) {
            //console.log(res);
            app.alert(res.errMsg);
          },
          complete:function(){
            wx.hideToast();
          }
        })
      }
    })
  },
  downloadFile: function (url, type ="logotemp"){
    var that = this;
    wx.downloadFile({
      url: url,  
      complete:function(){
        wx.hideToast();
      },
      fail:function(res){
        app.alert(res.errMsg);
      },
      success: function (res) {
        console.log(res);
        wx.hideToast();
        if (res.statusCode === 200) {
          if (type == "logotemp"){
            that.data.logotemp = res.tempFilePath;
          }else{
            that.data.pictemp = res.tempFilePath;
            wx.getImageInfo({
              src: res.tempFilePath,
               success: function (res) {
                 that.setData({coverInfo:res});
              }
            })
          } 
        }else{
          app.alert(res.errMsg);
          console.log(res);
        }
      }
    })
   
    
  }

})